package org.txazo.blog.commons.scan;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.txazo.blog.util.ContextUtil;

/**
 * StaticResourceUriScanner
 * 
 * @author Tu XiaoZhou
 * @since 2013-09-05
 * 
 */
public class StaticResourceUriScanner implements UriScanner {

	/** JS文件后缀 */
	private String jsType = "js";
	/** CSS文件后缀 */
	private String cssType = "css";
	/** 图片文件后缀 */
	private String imageType = "png^jpg^gif";
	/** 静态资源URI */
	private Set<String> uris = new HashSet<String>();

	@Override
	public Set<String> scan() {
		scan(new File(ContextUtil.getJSPath()), jsType, "/js");
		scan(new File(ContextUtil.getCssPath()), cssType, "/css");
		scan(new File(ContextUtil.getImagePath()), imageType, "/images");

		return uris;
	}

	private void scan(File parent, String type, String path) {
		File[] childs = parent.listFiles();
		for (File child : childs) {
			String name = child.getName();
			if (child.isDirectory()) {
				scan(child, type, path + "/" + name);
			} else if (child.isFile() && matchName(name, type)) {
				uris.add(path + "/" + name);
			}
		}
	}

	private boolean matchName(String name, String type) {
		int index = name.lastIndexOf(".");
		if (index != -1) {
			return type.contains(name.substring(index + 1, name.length()));
		}
		return false;
	}

}
